<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/26 0026
 * Time: 下午 2:53
 */
namespace app\message\model;
use think\console\command\make\Model;
use think\Db;

class Chat_mes extends Model{
    #添加
    public function add($data){
        $add = Db::name('chat_message')->insertGetId($data);
        return $add;
    }
    #修改
    public function del($data){
        $update = Db::name('chat_message')->where(['id'=>$data['id'],'del'=>1])->update(['del'=>2]);
        return $update;
    }
    #列表
    public function chat_list($data){
        $where = 'cm.del=1';
        $where.= isset($data['keyword'])?' and CONCAT(cm.content) like "%'.$data['keyword'].'%"':'';
        $where.= ' and cm.pid=0';
        #总条数
        $total = Db::name('chat_message')
            ->alias('cm')
            ->join('member m','m.id=cm.uid')
            ->where($where)->count();
        #总页数
        $page = ceil($total/$data['limits']);
        if ($data['curr']>$page){
            $data['curr']=$page;
        }
        #内容
        $field = 'm.username,cm.id,cm.content,cm.uid,cm.pid,cm.createtime';
        $list = Db::name('chat_message')
            ->alias('cm')
            ->join('member m','m.id=cm.uid')
            ->field($field)
            ->where($where)->page($data['curr'],$data['limits'])
            ->order(['id'=>'desc'])
            ->select();

        foreach ($list as $k =>$v){
            $list[$k]['children']=Db::name('chat_message')
                ->alias('cm')
                ->join('member m','m.id=cm.uid')
                ->field($field)
                ->where(['pid'=>$v['id']])
                ->page($data['curr'],$data['limits'])->select();
        }
        #返回
        $res = [
            'list'  =>$list,
            'total' =>$total,
            'page'  =>$page,
            'curr'  =>$data['curr'],
            'limits'=>$data['limits']
        ];

        return $res;
    }
}